import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';
import * as bcrypt from 'bcryptjs';
import { BusinessException } from '@/common/excepetion';
import { User } from '@/user/entities/user.entity';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async validateUser(account: string, password: string): Promise<User | null> {
    const user = await this.userService.findByAccount(account);
    if (!user) {
      return null;
    }
    if (!user.password) {
      return null;
    }
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return null;
    }
    return user;
  }

  async login(user: User) {
    if (!user || !user.id) {
      throw new BusinessException({ msg: '用户信息无效' });
    }
    const payload = { userId: user.id, account: user.account };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}
